package com.FOD.fragments;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import com.FOD.clases.R;
import com.FOD.clases.globalFunctions;
import com.FOD.entities.EmpleadoHorario;
import com.FOD.entities.PacienteUsuario;
import com.FOD.entities.User;
import com.FOD.util.SessionDBHandler;
import com.FOD.web.UsersFunctions;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class EditPatientFragment extends Fragment{
	View rootView;
	EditText nickname_edit;
	EditText name_edit;
	EditText last_name_edit;
	EditText mail_edit;
	EditText age_edit;
	Spinner sex_edit;
	EditText dependency_edit;
	EditText sport_edit;
	EditText phone_edit;
	TimePicker timeIn_edit;
	TimePicker timeOut_edit;
	Button editAction;
	User mUser = new User();

	EditText ocupation;
	Spinner civilState;
	CheckBox smocking;
	Spinner studies;
	Spinner bloodType;
	CheckBox alcohol;
	PacienteUsuario mPatient = new PacienteUsuario();

	UsersFunctions userFunctions = new UsersFunctions();
	SessionDBHandler db;
	ProgressDialog pDialog;
	PacienteUsuario mPacienteUsuario = new PacienteUsuario();
	globalFunctions globalFunctions = new globalFunctions();


	public EditPatientFragment() {}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.edit_user_patient, container, false);

		db = new SessionDBHandler(rootView.getContext());

		nickname_edit = (EditText)rootView.findViewById(R.id.nickname_patient_edit);
		name_edit = (EditText) rootView.findViewById(R.id.name_patient_edit);
		mail_edit = (EditText)rootView.findViewById(R.id.mail_patient_edit);
		age_edit = (EditText)rootView.findViewById(R.id.age_patient_edit);
		sex_edit = (Spinner)rootView.findViewById(R.id.sex_patient_edit);
		dependency_edit = (EditText)rootView.findViewById(R.id.dependency_patient_edit);
		sport_edit = (EditText)rootView.findViewById(R.id.sport_patient_edit);
		phone_edit = (EditText)rootView.findViewById(R.id.phone_patient_edit);
		editAction = (Button)rootView.findViewById(R.id.patient_editAction);

		ocupation = (EditText)rootView.findViewById(R.id.ocupation_patient_edit);
		civilState = (Spinner)rootView.findViewById(R.id.civilState_patient_edit);
		smocking = (CheckBox)rootView.findViewById(R.id.smoking_patient_edit);
		studies = (Spinner)rootView.findViewById(R.id.studies_patient_edit);
		bloodType = (Spinner)rootView.findViewById(R.id.bloodType_patient_edit);
		alcohol = (CheckBox)rootView.findViewById(R.id.alcohol_patient_edit);



		//Asignar valores de sexo al Spinner sex_new
		ArrayAdapter<CharSequence> adapter_sexType = ArrayAdapter.createFromResource(rootView.getContext(),R.array.sex_types_spinner, android.R.layout.simple_spinner_item);
		sex_edit.setAdapter(adapter_sexType);

		SessionDBHandler db = new SessionDBHandler(rootView.getContext());
		mUser = db.getUserDetails();

		nickname_edit.setText(mUser.getNickname());
		name_edit.setText(mUser.getName());
		mail_edit.setText(mUser.getMail());
		age_edit.setText(String.valueOf(mUser.getAge()));
		sex_edit.setSelection(mUser.getSex());
		dependency_edit.setText(mUser.getDependecy());
		sport_edit.setText(mUser.getSport());
		phone_edit.setText(String.valueOf(mUser.getPhone()));

		mPatient = db.getPatientUserDetails();
		ocupation.setText(mPatient.getOcupacion());

		ArrayAdapter<CharSequence> adapter_civil_State = ArrayAdapter.createFromResource(rootView.getContext(),R.array.state_civil_spinner, android.R.layout.simple_spinner_item);
		civilState.setAdapter(adapter_civil_State);

		civilState.setSelection(mPatient.getEstadoCivil());
		smocking.setChecked((mPatient.isTabaquismo()) ? true : false);

		ArrayAdapter<CharSequence> adapter_studies = ArrayAdapter.createFromResource(rootView.getContext(),R.array.studies_spinner, android.R.layout.simple_spinner_item);
		studies.setAdapter(adapter_studies);

		studies.setSelection(mPatient.getEscolaridad());

		ArrayAdapter<CharSequence> adapter_bloodType = ArrayAdapter.createFromResource(rootView.getContext(),R.array.blood_type_spinner, android.R.layout.simple_spinner_item);
		bloodType.setAdapter(adapter_bloodType);

		bloodType.setSelection(mPatient.getConverterBloodTypeToInt(mPatient.getDominancia(), rootView.getContext()));
		alcohol.setChecked((mPatient.isAlcoholismo()) ? true : false);

		editAction.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mUser.setNickname(nickname_edit.getText().toString());
				mUser.setName(name_edit.getText().toString());
				mUser.setMail(mail_edit.getText().toString());
				mUser.setAge(Integer.valueOf(age_edit.getText().toString()));
				mUser.setSex(mUser.getConverterSexToInt(sex_edit.getSelectedItem().toString(), rootView.getContext()));
				mUser.setDependecy(dependency_edit.getText().toString());
				mUser.setSport(sport_edit.getText().toString());
				mUser.setPhone(Integer.valueOf(phone_edit.getText().toString()));

				Log.i("MEEESSSTOOO", String.valueOf(mPacienteUsuario.getConverterCivilStatenToInt(civilState.getSelectedItem().toString(), rootView.getContext())));
				mPatient.setOcupacion(ocupation.getText().toString());
				mPatient.setEstadoCivil(mPacienteUsuario.getConverterCivilStatenToInt(civilState.getSelectedItem().toString(), rootView.getContext()));
				mPatient.setTabaquismo((smocking.isChecked()) ? true : false);
				mPatient.setEscolaridad(mPacienteUsuario.getConverterStudiesToInt(studies.getSelectedItem().toString(), rootView.getContext()));
				mPatient.setDominancia(bloodType.getSelectedItem().toString());
				mPatient.setAlcoholismo((alcohol.isChecked()) ? true : false);
				new editUser().execute(mUser, mPatient);				
			}
		});

		return rootView;
	}

	//**************************

	private class editUser extends AsyncTask<Object, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Object... params) {
			User userToEdit = (User) params[0];
			PacienteUsuario mPacienteToEdit = (PacienteUsuario) params[1];
			return userToEdit(userToEdit, mPacienteToEdit);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(rootView.getContext());
			pDialog.setMessage("Editando usuario...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		public Boolean userToEdit(User userToEdit, PacienteUsuario patientToEdit){
			JSONObject json = userFunctions.editUser(userToEdit);
			try {
				if(json.getInt("error") == 0){

					JSONObject json_user = json.getJSONObject("user");

					patientToEdit.setUsuario_id(json_user.getInt("id"));


					JSONObject json_employe = userFunctions.editPatient(patientToEdit);
					json_employe = json_employe.getJSONObject("user");

					setUserToMemory(json_user);
					setPatientToMemory(json_employe);
					db.close();
				}else{
					Toast.makeText(rootView.getContext(), "Ocurrio un error al agregar el usuario", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (pDialog.isShowing()){
				pDialog.dismiss();
			}
			if(result){
				Toast.makeText(rootView.getContext(), "El usuario se ha editado con exito", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(rootView.getContext(), "Ocurrio un error al editar el usuario", Toast.LENGTH_SHORT).show();
			}
			globalFunctions.closeKeyboard(rootView.getContext(), rootView.getWindowToken());
			Fragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
		}
	}


	public void setUserToMemory(JSONObject json_user){
		db.resetTables();
		User mUser = new User();
		try {
			mUser.setId(json_user.getInt("id"));
			mUser.setNickname(json_user.getString("nickname"));
			mUser.setPassword(json_user.getString("password"));
			mUser.setName(json_user.getString("name"));
			mUser.setMail(json_user.getString("mail"));
			mUser.setType(json_user.getInt("user_type"));
			mUser.setAge(json_user.getInt("age"));
			mUser.setSex(json_user.getInt("sex"));
			mUser.setDependecy(json_user.getString("dependency"));
			mUser.setSport(json_user.getString("sport"));
			mUser.setPhone(Long.valueOf((json_user.getInt("phone"))));
			SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date d1 = dateFormatOfStringInDB.parse(json_user.getString("create_date"));
				mUser.setCreateDate(d1);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			db.addUser(mUser);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setPatientToMemory(JSONObject json_employee){
		PacienteUsuario eh = new PacienteUsuario();

		try {
			eh.setId(json_employee.getInt("id"));
			eh.setUsuario_id(json_employee.getInt("usuario_id"));
			eh.setOcupacion(json_employee.getString("ocupacion"));
			eh.setEstadoCivil((Integer.valueOf(json_employee.getString("estado_civil"))));
			eh.setTabaquismo(((json_employee.getString("tabaquismo").equals("1")) ? true : false));
			eh.setEscolaridad(Integer.valueOf(json_employee.getString("escolaridad")));
			eh.setDominancia(json_employee.getString("dominancia"));
			eh.setAlcoholismo( (json_employee.getString("alcoholismo").equals("1") ? true : false) );
			
			db.addPatientUser(eh);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
